<template>
  <el-dialog v-model="dialogVisible" title="修改商标信息" width="500" draggable>
    <el-form :model="form" label-width="80px">
      <!-- Brand Name -->
      <el-form-item label="商标名称">
        <el-input v-model="form.brandName" autocomplete="off"/>
      </el-form-item>
      <!-- Brand Website -->
      <el-form-item label="商标网址">
        <el-input v-model="form.brandNet" autocomplete="off"/>
      </el-form-item>
      <!-- Brand Image -->
      <el-form-item label="商标图片">
        <div v-if="isShowOld">
          <img class="pic" :src="form.brandImg" alt=""/>
          <el-button type="primary" @click="updateImg">修改图片</el-button>
        </div>
        <div v-else>
          <upload ref="uploadComponent" @upload-success="handleUploadSuccess"></upload>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {defineProps, defineEmits, watch, reactive, computed, ref} from 'vue';
import {deleteFile} from '@/api/utils';
import {updateBrand} from '@/api/brand'; // 假设这是你的品牌更新API
import upload from "@/components/upload.vue";
import {ElMessage} from "element-plus";
import {headImgStore} from "@/store/tokenStore"

const headImg = headImgStore();
// 定义props
const props = defineProps({
  drawerVisible: Boolean,
  brand: {
    type: Object as () => {
      brandId: number;
      brandName: string;
      brandNet: string;
      brandImg: string;
    },
    required: true
  }
});

// 定义emits
const emit = defineEmits(['update:drawerVisible', 'formSubmitted']);

// 初始化表单数据
const form = reactive({...props.brand});

// 监听 props 变化，当有新的 brand 传入时更新表单
watch(() => props.brand,
    (newVal) => {
  if (newVal) {
    Object.assign(form, newVal);
  }
},
    {immediate: true, deep: true}
);

// 计算属性来同步 dialogVisible 和父组件的状态
const dialogVisible = computed({
  get: () => props.drawerVisible,
  set: (value) => emit('update:drawerVisible', value)
});

// 控制是否显示旧封面
const isShowOld = ref(true);


// 更新图片的方法
const updateImg = async () => {
  isShowOld.value = false;
};

// 关闭对话框的方法
const closeDialog = () => {
  dialogVisible.value = false;
};

// 引用子组件实例
const uploadComponent = ref<InstanceType<typeof upload> | null>(null);

// 图片上传成功的回调方法
const handleUploadSuccess = () => {
  // 这里可以添加处理上传成功的逻辑
};

// 提交编辑的方法
const submitEdit = async () => {
  try {
    let tempImg = form.brandImg;
    if (uploadComponent.value && !isShowOld.value) {
      // 使用Promise等待上传完成
      const uploadPromise = new Promise<void>((resolve, reject) => {
        let unwatch: (() => void) | null = null; // 提前声明unwatch
        unwatch = watch(
            () => headImg.headImg,
            (newVal) => {
              if (newVal) {
                if (unwatch) unwatch(); // 确保unwatch已初始化
                resolve();
              }
            },
            {immediate: true}
        );

        // 调用子组件的manualUpload方法并立即启动上传
        uploadComponent.value.manualUpload();
      });

      await uploadPromise; // 等待上传完成
    }
    if (headImg.headImg !== '') {
      form.brandImg = headImg.headImg;
    } else {
      form.brandImg = tempImg;
    }
    // 更新品牌信息
    await updateBrand(form, form.brandId);
    emit('formSubmitted');
    closeDialog();
    deleteImg(tempImg)
    isShowOld.value = true;
    headImg.clearHeadImg()
  } catch (error) {
    ElMessage.error('提交失败，请检查输入信息或网络连接');
    console.error(error); // 记录错误信息，方便调试
  }
};
const deleteImg = async (tempImg) => {
  let fileName = tempImg.split('/').pop();
  if (fileName) {
    const res = await deleteFile(fileName);
  }
};
</script>

<style scoped>
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-title {
  font-size: 18px;
  font-weight: bold;
}

.pic {
  width: 100px;
  height: 100px;
}
</style>